package call;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public class CallStoreProc {
	private static Connection connection;

	public static void main(String[] args) {
		try {
			// load driver
			// Class.forName("net.sourceforge.jtds.jdbc.Driver");
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			System.out.println("driver da duoc load ");
			// tao ket noi den CSDL
			// Connection connection = DriverManager.getConnection(
			// "jdbc:jtds:sqlserver://localhost:1433/test", "sa",
			// "sa");
			connection = DriverManager
					.getConnection("jdbc:sqlserver://BDK-PC;databaseName=demo;user=sa;password=123456");
			System.out.println("Da ket noi duoc voi CSDL");
			// tao cau truy van
			testGetAll();
			// testInsert();

		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		} catch (SQLException ex) {
			ex.printStackTrace();
		}

	}

	private static void testInsert() throws SQLException {
		String sql = "{ call insertABC(?,?,?) }";
		// thuc hien cau truy van
		CallableStatement state = connection.prepareCall(sql);
		state.setInt(1, 2);
		state.setString(2, "longle");
		state.setDate(3, new java.sql.Date(new java.util.Date().getTime()));

		System.out.println(state.execute());
	}

	private static void testGetAll() throws SQLException {
		String sql = "{ call sp_sinhvien_SelectAll }";
		CallableStatement state = connection.prepareCall(sql);
		// ket qua tra ve la tap hop cac dong
		// ResultSet result = state.executeQuery();
		ResultSet result = state.executeQuery();

		while (result.next()) {
			System.out.println(result.getString(1) + "\t" + result.getString(3)
					+ "\t");
		}

		ResultSetMetaData data = result.getMetaData();
		int column = data.getColumnCount();
		for (int i = 1; i < column; i++) {
			// System.out.println(data.getColumnLabel(i));
		}
	}
}
